package week_02;

public class myPow_50 {
    public double myPow2(double x, int n) {
        //实现 pow(x, n) ，即计算 x 的 n 次幂函数（即，xn）
        if (n > 0) {
            return pow(x, n);
        } else if (n < 0) {
            return 1 / pow(x, -n);
        } else {
            return 1.0;
        }
    }

    public double pow(double x, int n) {
        if (n == 0) return 1;
        double temp = pow(x, n / 2);
        if (n % 2 == 0) {
            return temp * temp;
        } else {
            return temp * temp * x;
        }
    }

    public double myPow(double x, long n) {
        //实现 pow(x, n) ，即计算 x 的 n 次幂函数（即，xn）
        if (n < 0) {
            return 1 / myPow(x, -n);
        }
        if (n == 0) {
            return 1;
        }
        double temp = myPow(x, n / 2);
        if (n % 2 == 0) {
            return temp * temp;
        } else {
            return temp * temp * x;
        }
    }

    // old
    public double myPow33(double x, int n) {
        if (n == 0) return 1;
        if (n % 2 == 0) return myPow(x, n / 2) * myPow(x, n / 2);
        if (n % 2 == 1) return myPow(x, n / 2) * myPow(x, n / 2) * x;
        if (n < 0) return (1 / myPow(x, -n));
        return -1;
    }

    public double myPow22(double x, int n) {
        if (n == 0) return 1;
        if (n % 2 == 0) return myPow(x, n / 2) * myPow(x, n / 2);
        if (n % 2 == 1) return myPow(x, n / 2) * myPow(x, n / 2) * x;
        if (n < 0) return (1 / myPow(x, -n));
        return -1;
    }

    public double pow2(double x, int n) {
        double[] ans = new double[n + 1];
        ans[0] = 1;
        for (int i = 1; i <= n; i++) {
            if (i % 2 == 0) ans[i] = ans[i / 2] * ans[i / 2];
            if (i % 2 == 1) ans[i] = ans[i / 2] * ans[i / 2] * x;
        }
        return ans[n];
    }

    public double pow1(double x, int n) {
        // x^2 x^4 x^8 x^16 ...
        // 处理越界
        if (x == 0.0F) return 0.0d;
        long d = n;
        if (d < 0) {
            d = -d;
            x = 1 / x;
        }
        double ans = 1.0;
        while (d > 0) {
            if (d % 2 == 1) ans *= x;
            x *= x;
            d = d >> 1;
        }
        return ans;
    }

}
